import { store } from "@/store";
import { defineStore } from "pinia";
import FieldApi, { type FieldListParams, type FieldType } from "@/api/system/field";

export const useFieldStore = defineStore("field", () => {
  const list = ref<FieldType[]>([]);

  const totalCount = ref(0);

  const totalPage = ref(0);

  const loading = reactive({
    list: false,
    detail: false,
    create: false,
    update: false,
    delete: false,
  });

  async function fetchFieldList(params: FieldListParams) {
    loading.list = true;
    const response = await FieldApi.getFieldList(params);
    loading.list = false;
    if (response) {
      list.value = response.records;
      totalCount.value = response.total_count;
      totalPage.value = response.total_page;
    }
  }

  async function fetchFieldDetail(id: number) {
    loading.detail = true;
    const response = await FieldApi.fieldDetail(id);
    loading.detail = false;
    if (response) {
      list.value = [response];
    }
  }

  async function fetchCreateField(Field: Partial<FieldType>) {
    loading.create = true;
    await FieldApi.addField(Field);
    loading.create = false;
  }

  async function fetchUpdateField(Field: Partial<FieldType>) {
    loading.update = true;
    await FieldApi.updateField(Field);
    loading.update = false;
  }

  async function fetchDeleteField(id: number) {
    loading.delete = true;
    await FieldApi.deleteField(id);
    loading.delete = false;
  }

  return {
    list,
    totalCount,
    totalPage,
    loading,
    fetchFieldList,
    fetchFieldDetail,
    fetchCreateField,
    fetchUpdateField,
    fetchDeleteField,
  };
});

export const useFieldStoreHook = () => {
  return useFieldStore(store);
};
